package com.yy.jhl.ui.main.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.view.View;

import com.yy.common.base.BaseActivity;
import com.yy.common.commonwidget.ClipImageLayout;
import com.yy.common.commonwidget.OnNoDoubleClickListener;
import com.yy.jhl.R;

import butterknife.BindView;

/**
 * Created by Ellis.Li on 2017/7/28.
 */

public class ClipImageActivity extends BaseActivity {

    public static int CLIP_RESULT_OK = 1234;
    private static int IMAGE_MAX_WIDTH = 720;
    private static int IMAGE_MAX_HEIGHT = 1280;
    @BindView(R.id.clipImageLayout)
    ClipImageLayout clipImageLayout;
    Uri imageUri;
    public static void startAction(Activity mContext, Uri imageUri) {
        Intent intent = new Intent(mContext, ClipImageActivity.class);
        intent.putExtra("imageUri", imageUri);
        mContext.startActivityForResult(intent,CLIP_RESULT_OK);
    }
    @Override
    public int getLayoutId() {
        return R.layout.act_clip_image;
    }

    @Override
    public void initView() {
        showTitle("裁剪图片", new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                finish();
            }
        });
        showRightBtn("确定", new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                saveEvent();

            }
        });
        imageUri = (Uri)getIntent().getParcelableExtra("imageUri");
        String imagePath =imageUri.getPath();
        BitmapFactory.Options option = new BitmapFactory.Options();
        option.inSampleSize = getImageScale(imagePath);
        Bitmap  bitmap = BitmapFactory.decodeFile(imagePath, option);
        clipImageLayout.getZoomImageView().setImageBitmap(bitmap);

    }
    private static int getImageScale(String imagePath) {
        BitmapFactory.Options option = new BitmapFactory.Options();
        // set inJustDecodeBounds to true, allowing the caller to query the bitmap info without having to allocate the
        // memory for its pixels.
        option.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imagePath, option);

        int scale = 1;
        while (option.outWidth / scale >= IMAGE_MAX_WIDTH || option.outHeight / scale >= IMAGE_MAX_HEIGHT) {
            scale *= 2;
        }
        return scale;
    }
    private void saveEvent(){
        Bitmap saveBitmap = clipImageLayout.clip();
        Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), saveBitmap, null,null));
        Intent intent = new Intent();
        intent.putExtra("imageUri",uri);
        setResult(RESULT_OK,intent);
        finish();
    }
}
